package com.example.blog.util.TokenUtil;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtils {
  private static final String KEY = "QWERYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890";
  public static final String USER_NAME_KEY = "username";

  public static String createToken(String username) {
    Map<String, Object> claims = new HashMap<>();
    claims.put(USER_NAME_KEY, username);
    String token = Jwts.builder()
            .signWith(SignatureAlgorithm.HS256, KEY)
            .setClaims(claims)
            .setIssuedAt(new Date())
            .setExpiration(new Date(System.currentTimeMillis() + 24L * 60 * 60 * 1000 * 7))
            .compact();
    return token;
  }

  public static Claims parseJWT(String token) {
    return Jwts.parser()
            .setSigningKey(KEY)
            .parseClaimsJws(token)
            .getBody();
  }

  public static String getUserName(Claims claims) {
    if (claims != null) {
      return (String) claims.get(USER_NAME_KEY);
    }
    return null;
  }

  public static boolean verifyToken(String token) {
    try {
      Jwts.parser().setSigningKey(KEY).parseClaimsJws(token);
      return true;
    } catch (Exception e) {
      // Token verification failed
      return false;
    }
  }
}

